import React, { useState, useEffect } from "react";
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons";
import "./index.less";
import { Layout, Button, Modal } from "antd";
import { useNavigate, useLocation } from "react-router-dom";
import axios from "axios";
import storageUtils from "../../utils/storageUtils";
const { confirm } = Modal;
const { Header } = Layout;

const MHeader = ({ collapsed, toggleCollapsed }) => {
  const navigate = useNavigate();
  const location = useLocation();
  const [currentTime, setCurrentTime] = useState("");
  const [weather, setWeather] = useState("");
  const [weatherIcon, setWeatherIcon] = useState("");

  useEffect(() => {
    const updateCurrentTime = () => {
      const now = new Date();
      const date = now.toLocaleDateString();
      const time = now.toLocaleTimeString();
      const formattedTime = `${date} ${time}`;
      setCurrentTime(formattedTime);
      setCurrentTime(formattedTime);
    };

    updateCurrentTime();
    const timer = setInterval(updateCurrentTime, 1000);

    return () => clearInterval(timer);
  }, []);

  useEffect(() => {
    const fetchWeather = async () => {
      try {
        const apiKey = "2e1831dad5b94f4fa61809fa47974785"; // 替换为你的和风天气 API 密钥
        const city = "101190104"; // 可以替换为其他中国城市
        const url = `https://devapi.qweather.com/v7/weather/now?location=${city}&key=${apiKey}`;
        const response = await axios.get(url);
        console.log(response);
        const weatherDescription =
          response.now.text + "," + response.now.temp + "°C";
        setWeather(weatherDescription);

        // 设置天气图标（示例）
        const iconCode = response.now.icon;
        const iconUrl = `/icons/${iconCode}.svg`; // 使用公共路径
        setWeatherIcon(iconUrl);
      } catch (error) {
        console.error("获取天气信息失败:", error);
        setWeather("未知");
      }
    };
    fetchWeather();
  }, []);

  const logout = () => {
    confirm({
      title: "确定要退出登录吗？",
      icon: <ExclamationCircleOutlined />,
      content: "",
      onOk() {
        storageUtils.removeUser();
        navigate("/login", { replace: true });
      },
      onCancel() {
        console.log("Cancel");
      },
    });
  };

  const getTitle = (pathname) => {
    switch (pathname) {
      case "/home":
        return "首页";
      case "/products/category":
        return "品类管理";
      case "/products/product":
        return "商品管理";
      case "/user":
        return "用户管理";
      case "/role":
        return "角色管理";
      case "/charts/bar":
        return "柱形图";
      case "/charts/line":
        return "线形图";
      case "/charts/pie":
        return "饼图";
      default:
        return "首页";
    }
  };

  const title = getTitle(location.pathname);
  const user = storageUtils.getUser();

  return (
    <Header
      className="site-layout-background"
      style={{
        background: "#fff",
        padding: 0,
      }}
    >
      <div className="header">
        <h2 className="header-title">{title}</h2>
        <div className="header-user">
          <div className="currentTime">{currentTime}</div>
          <div className="weather">{weather}</div>
          <div className="weatherPic">
            {weatherIcon && <img src={weatherIcon} alt="Weather Icon" />}
          </div>
          <div className="userInfo">
            欢迎,{user.username}
            <Button onClick={logout}>退出</Button>
          </div>
        </div>
      </div>
      {React.createElement(collapsed ? MenuUnfoldOutlined : MenuFoldOutlined, {
        className: "trigger",
        onClick: toggleCollapsed,
      })}
    </Header>
  );
};

export default MHeader;
